package com.xwks.provider;

import com.xwks.entity.User;
import com.xwks.service.UserService;
import com.xwks.util.ApplicationContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class CustomerAuthenticationProvider implements AuthenticationProvider {


    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        PasswordEncoder passwordEncoder = ApplicationContextUtil.getBean(PasswordEncoder.class);
        String username = authentication.getName();
        String presentedPassword = (String) authentication.getCredentials();
        UserDetails userDeatils = null;
        // 根据用户名获取用户信息
        User user = userService.getUserByUsername(username);
        if (Objects.isNull(user)) {
            throw new BadCredentialsException("用户名不存在");
        } else {
            userDeatils = new org.springframework.security.core.userdetails.User(username, passwordEncoder.encode(user.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole()));
            // 自定义的加密规则，用户名、输的密码和数据库保存的盐值进行加密
            //String encodedPassword = passwordEncoder.encode(user.getPassword());
            if (authentication.getCredentials() == null) {
                throw new BadCredentialsException("登录名或密码错误");
            } else if (!passwordEncoder.matches(user.getPassword(), userDeatils.getPassword())) {
                throw new BadCredentialsException("登录名或密码错误");
            } else {
                UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDeatils, authentication.getCredentials(), userDeatils.getAuthorities());
                result.setDetails(authentication.getDetails());
                return result;
            }
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
